#!/bin/bash
USERNAME="zyk" # New User Name
SHELLNAME="/usr/bin/zsh" # Default shell for $USERNAME
HOSTNAME="zyk-PC" # /etc/hostname


COUNTRY="CN" #"AU" "AT" "BD" "BY" "BE" "BA" "BR" "BG" "CA" "CL" "CN" "CO" "HR" "CZ" "DK" "EC" "FI" "FR" "DE" "GR" "HK" "HU" "IS" "IN" "ID" "IR" "IE" "IL" "IT" "JP" "KZ" "LV" "LT" "LU" "MK" "MX" "AN" "NC" "NZ" "NO" "PH" "PL" "PT" "QA" "RO" "RU" "RS" "SG" "SK" "SI" "ZA" "KR" "ES" "SE" "CH" "TW" "TH" "TR" "UA" "GB" "US" "VN"
TIMEZONE_REGION="Asia"    #/etc/locale.time
TIMEZONE_CITY="Shanghai"  #/etc/locale.time
LOCALE_GEN="zh_CN.UTF-8 en_US.UTF-8" #/etc/locale.gen
LANG="en_US.UTF-8" #etc/locale.conf
CN_MIRROR="TUNA" #USTC 163 TUNA


DiskDev="null"      # 1.null: later Select  2./dev/sd*

#PartConfigur：  boot  root    swap   home 的顺序就是 /dev/sda* 的顺序，一定一定要是一致的，不能搞错
# 更改PartConfigure 分区的顺序时也要更改GenPartInfo 中的 DiskPartIndex 序号，要保证和PartConfigure 中顺序一致
# PartName 与　GenPartTable　中的分区表顺序和名字需要一一对应
# Advance Professioal Users
# Custom self partition config
#PartConfigure="null";
PartConfigure="boot root swap home"
function GenPartInfo()
{

cat << EOF > $GenPartPath
Name    FsType     isFormat   DiskPartIndex       MountPoint    Start(M)      End(M)

boot     fat        1         /dev/sda1      /boot      0             500

root     ext4       1         /dev/sda2      /          500           10000

swap     swap       1         /dev/sda3      swap       10000         11000

home     ext4       0         /dev/sda4      /home      11000          100%

EOF

}


##### User Config End #####


function color_echo()
{
    while (($#!=0))
    do
            case $1 in
                    -b)
                            echo -ne " ";
                    ;;
                    -t)
                            echo -ne "\t";
                    ;;
                    -n)     echo -ne "\n";
                    ;;
                    -black)
                            echo -ne "\033[30m";
                    ;;
                    -red)
                            echo -ne "\033[31m";
                    ;;
                    -green)
                            echo -ne "\033[32m";
                    ;;
                    -yellow)
                            echo -ne "\033[33m";
                    ;;
                    -blue)
                            echo -ne "\033[34m";
                    ;;
                    -purple)
                            echo -ne "\033[35m";
                    ;;
                    -cyan)
                            echo -ne "\033[36m";
                    ;;
                    -white|-gray) echo -ne "\033[37m";
                    ;;
                    -reset)
                            echo -ne "\033[0m";
                    ;;
                    -h|-help|--help)
                            echo "Usage: color_echo -color1 message1 -color2 message2 ...";
                            echo "eg:       color_echo -red [ -blue message1 message2 -red ]";
                    ;;
                    *)
                    echo -ne "$1"
                    ;;
            esac
            shift
    done
}

##### const runtime depend
GenPartPath="/root/part.list"


function _DecideDiskDevice()
{
    DiskNum=`lsblk | grep -E '^sd' | wc -l`

    color_echo -green "Found: $DiskNum Disks Device: \n" -reset -n
    lsblk | grep -E '^sd|NAME' | awk '{print $1 "   :    " $4"   :   "$6}'


    list=""
    for i in `lsblk | grep -E '^sd' | awk '{print $1 "  :   " $4}' | awk '{print $1}'`;
    do
        list="$list $i"
    done

    color_echo -yellow "\n\nWhich disk you want install ArchLinux ?(sd*): " -green "$list" -reset -n

    color_echo "Plese input:  "
    read choose


    for i in $list;
    do
        if [ "$i" == "$choose" ];then
            DiskDev="/dev/$i"
            break
        fi
    done
}
function DecideDiskDevice()
{
   if [ $DiskDev != "null" ];then
        return
   fi
   _DecideDiskDevice
   while [ $DiskDev == "null" ];do
        color_echo -red "\nINPUT ERROR: DiskDev is null, please retry input \n\n\n" -reset -n
        _DecideDiskDevice
   done
}

function FormatMountPartition()
{
        partInfoItem=`cat $GenPartPath | grep -E "^*$1"`
        echo $partInfoItem
        partInfoName=`echo $partInfoItem | awk '{print $1}'`
        partInfoFstype=`echo $partInfoItem | awk '{print $2}'`
        partInfoIsFormat=`echo $partInfoItem | awk '{print $3}'`
        partInfoPartIndex=`echo $partInfoItem | awk '{print $4}'`
        partInfoMountPoint=`echo $partInfoItem | awk '{print $5}'`

        if [ $partInfoIsFormat == "1" ];then
            if [ $partInfoFstype == "swap" ];then
                color_echo -reset "mkswap on $partInfoPartIndex" -n
                swapoff $partInfoPartIndex > /dev/null 2>&1
                mkswap $partInfoPartIndex -f
            elif [ $partInfoFstype == "fat" ];then
                color_echo -reset " mkfs.fat on $partInfoPartIndex" -n
                mkfs.fat -F32 $partInfoPartIndex
            else
                color_echo -reset " mkfs.$partInfoFstype on $partInfoPartIndex" -n
                mkfs.$partInfoFstype  $partInfoPartIndex
            fi
        fi

        if [ "$i" == "root" ];then
             umount /mnt > /dev/null 2>&1
             umount $partInfoPartIndex > /dev/null 2>&1
             mount $partInfoPartIndex /mnt
        elif [ "$i" == "swap" ];then
             swapon $partInfoPartIndex
        else
             umount /mnt$partInfoMountPoint > /dev/null 2>&1
             umount $partInfoPartIndex > /dev/null 2>&1
             mkdir -p /mnt$partInfoMountPoint
             mount $partInfoPartIndex /mnt$partInfoMountPoint
        fi
}

function GenPartInfoTable()
{
   partInfo_fixed=0
   rm -rf $GenPartPath
   partInfoNameList=""
   while [ $partInfo_fixed == "0" ];do

       if [ "$PartConfigure" != "null" ];then
            GenPartInfo
            partInfoNameList=$PartConfigure
       else
           color_echo -yellow "Please input new parts info: \n"
           color_echo -cyan "PartName:root,home,boot,swap,etc...\n"
           color_echo "Fstype:ext4,ext3,ext2,fat\n"
           color_echo "IsFormat:0,1\n"
           color_echo "PartIndex:/dev/sd**\n"
           color_echo "MountPoint:/ /boot /home swap\n"
           color_echo "\nPartName    FsType  IsFormat  PartIndex   MountPoint\n\n"
           read partinfo

            partInfoName=`echo $partinfo | awk '{print $1}'`
            partInfoFstype=`echo $partinfo | awk '{print $2}'`
            partInfoIsFormat=`echo $partinfo | awk '{print $3}'`
            partInfoPartIndex=`echo $partinfo | awk '{print $4}'`
            partInfoMountPoint=`echo $partInfoItem | awk '{print $5}'`

            echo $partinfo >> $GenPartPath
            partInfoNameList="$partInfoNameList $partInfoName"
       fi

        color_echo -yellow "PartInfo is ok ?,Please Check again! (yes/no)"
        fdisk -l $DiskDev | grep -iE "^$DiskDev|Disklabel|Disk model|Disk $DiskDev|^Device"
        color_echo -reset -n -n
        cat $GenPartPath
        read yes_no

        if [ $yes_no = "yes" ];then
            partInfo_fixed="1"
        fi

   done

}

function PartDiskDevice()
{
   if [ $DiskDev == "null" ];then
        color_echo -red "\n ERROR PartDiskDevice: DiskDev is NULL \n\n\n" -reset -n
        exit
   fi
   part_num=`fdisk -l $DiskDev | grep -E "^/dev/$1" | wc -l`
   diskLabel=`fdisk -l $DiskDev | grep -E "Disklabel type" | awk '{print $3}'`

   echo "partition table:"$diskLabel
   echo "partition number:"$part_num


   while [ "$diskLabel" != "gpt" ];do
        color_echo "Create GPT partition table on $DiskDev ?(y/n,default:y)\n"
        read yes_no
        if [ "$yes_no" != "n" ];then
            parted -s -a optimal $DiskDev mklabel gpt
            if [ "$?" == "0" ];then
                diskLabel=`fdisk -l $DiskDev | grep -E "Disklabel type" | awk '{print $3}'`
            fi
        else
            color_echo "\n\nOnly Support GPT partition table in this scripts,Press Ctrl-C Exit.......\n\n" -n
        fi
   done

   part_fixed=0
   while [ $part_fixed == "0" ];do
        if [ $part_num == "0" ];then
            color_echo "\nDon't Found Any partition on $DiskDev\nHow Create Partition you want ?(0/1 default:1)\n       0: Using scripts GenPartInfo\n       1: Using cfdisk\n"
            read yes_no
            if [ "$yes_no" != "0" ];then
                cfdisk $DiskDev
            elif [ "$PartConfigure" != "null" ];then
                color_echo "Not Supported todo." -n
                GenPartInfo
                #TODO: 添加询问确认信息提示， 将这一段单独拎出来做一个函数
                for i in $PartConfigure;do
                        partInfoItem=`cat $GenPartPath | grep -E "^*$i"`
                        echo $partInfoItem
                        partName=`echo $partInfoItem | awk '{print $1}'`
                        partStart=`echo $partInfoItem | awk '{print $6}'`
                        partEnd=`echo $partInfoItem | awk '{print $7}'`
                        parted -s -a minimal $DiskDev mkpart primary $partStart $partEnd
                        part_num=`fdisk -l $DiskDev | grep -E "^/dev/$1" | wc -l`
                done
            fi
            part_num=`fdisk -l $DiskDev | grep -E "^/dev/$1" | wc -l`
        else
            color_echo -yellow "Please Check again parttion info follow, It's OK ?" -green "(yes/no:default: no)\n" -cyan "       YES: partion is ok,don't modify\n       NO: modify parttion again\n\n"
            color_echo -reset
            fdisk -l $DiskDev | grep -iE "^$DiskDev|Disklabel|Disk model|Disk $DiskDev|^Device"
            color_echo -reset -n -n
            color_echo "Plese input:  "
            read yes_no
            if [ "$yes_no" == "yes" ];then
                part_fixed="1"
            else
                color_echo -yellow "Do you want delete all exsit partitions ?" -green "(yes/no:default: no)\n" -cyan "       YES:delete all partition,Create from blank disk\n       NO: modify partition by cfdisk\n\n"
                color_echo -reset
                color_echo "Plese input:  "
                read yes_no
                if [ "$yes_no" == "yes" ];then
                    for part in `fdisk -l $DiskDev | grep -E "^$DiskDev" |awk '{print $1}'`;do
                        #echo "part:    $part"
                        swapoff $part > /dev/null 2>&1
                        umount $part > /dev/null 2>&1
                        part=`echo $part |tr -cd "0-9"`
                        parted -s -a minimal $DiskDev rm $part
                    done
                else
                    cfdisk $DiskDev
                fi
                part_num=`fdisk -l $DiskDev | grep -E "^/dev/$1" | wc -l`
            fi
        fi
   done

   GenPartInfoTable

   FormatMountPartition root
   for i in  $partInfoNameList;do
        if [ $i != "root" ];then
            FormatMountPartition $i
        fi
   done

   df -h

   part_num=`fdisk -l $DiskDev | grep -E "^/dev/$1" | wc -l`
   #fdisk -l $DiskDev
}


function PreparePartition()
{
    DecideDiskDevice
    PartDiskDevice

}

function ArchChroot()
{
    cp /root/arch_install.sh /mnt/root
    cp $GenPartPath /mnt/$GenPartPath
    chmod +x / /mnt/root/arch_install.sh
    arch-chroot /mnt /root/arch_install.sh --config

}



#############################################################


function GenHosts()
{

echo $HOSTNAME > /etc/hostname

cat << EOF > /etc/hosts

127.0.0.1   localhost
::1     localhost
127.0.1.1   myhostname.localdomain  myhostname

EOF

sed -i "s/myhostname/$HOSTNAME/g" /etc/hosts

cat /etc/hostname
cat /etc/hosts

}

ConfigGrub(){
    if (mount | grep efivarfs > /dev/null 2>&1);then
        pacman -S --noconfirm grub efibootmgr -y
        rm -f /sys/firmware/efi/efivars/dump-*
        grub-install --target=`uname -m`-efi --efi-directory=/boot/efi --bootloader-id=ArchLinux
        grub-mkconfig -o /boot/grub/grub.cfg
    else
        color_echo -red  "ERROR: install_grub Support Only UEFI Config"
    fi
}

function PreConfigArchLinux()
{
    ln -sf /usr/share/zoneinfo/$TIMEZONE_REGION/$TIMEZONE_CITY /etc/localtime

    hwclock --systohc --utc

    for locale in `echo $LOCALE_GEN`;do
        echo $locale
        sed -i "s/"#""$locale"/$locale/g" /etc/locale.gen
    done

    echo "LANG=$LANG" > /etc/locale.conf

    GenHosts

    color_echo  -green "Please Input Root Admin Passwd:\n" -reset

    passwd



    #ConfigGrub

    case $CN_MIRROR in
                "USTC")
                    echo -e "[archlinuxcn]\nServer = https://mirrors.ustc.edu.cn/archlinuxcn/\$arch" >> /etc/pacman.conf
                    break
                ;;
                "TUNA")
                    echo -e "[archlinuxcn]\nServer = https://mirrors.tuna.tsinghua.edu.cn/archlinuxcn/\$arch" >> /etc/pacman.conf
                    break
                ;;
                "163")
                    echo -e "[archlinuxcn]\nServer = http://mirrors.163.com/archlinux-cn/\$arch" >> /etc/pacman.conf
                    break
                ;;
                *)
                    color_echo -red "Don't install archlinuxcn source"
                ;;
    esac
}


function ConfigSougouInput()
{
   echo "TODO" ;

}


function ConfigTeamview()
{
   echo "TODO" ;
   sudo systemctl enable teamviewerd.service
}

function ConfigArchLinux()
{
    PreConfigArchLinux

    #InstallApplication

    ConfigNewUser

    pacman -S deepin deepin-extra deepin-terminal lightdm lightdm-gtk-greeter
    sed -i '108s/#greeter-session=example-gtk-gnome/greeter-session=lightdm-deepin-greeter/' /etc/lightdm/lightdm.conf

    systemctl enable NetworkManager

    systemctl enable dhcpcd

    systemctl enable lightdm



}


case $1 in
    --installApp)
        InstallApplication;;
    --config)
        ConfigArchLinux;;
    --chroot)
        ArchChroot;;
    *)
      InstallBaseCore;;
esac








